package com.mlming.springboot.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mlming.springboot.consts.MallConst;

import java.util.Base64;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    /**
     * 生成token
     * @param map 数据体, 即payload
     * @return
     */
    public static String getToken(Map<String,String> map) {
        // 过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, MallConst.TOKEN_EXPIRE_DATE_COUNT); // 默认三天过期
        // 创建JWT Builder
        JWTCreator.Builder builder = JWT.create();
        // 加载payload
        map.forEach((k,v) -> {
            builder.withClaim(k,v);
        });
        // 生成token
        String token = builder.withExpiresAt(calendar.getTime()) // 设置过期时间
                              .sign(Algorithm.HMAC256(MallConst.PRIVATE_SIGN)); // 设置签名
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verifyToken(String token) throws JWTVerificationException {
        JWT.require(Algorithm.HMAC256(MallConst.PRIVATE_SIGN)).build().verify(token);
    }

    /**
     * 获取token的payload对应的数据
     * @param token
     * @return
     */
    public static Map<String,String> getPayLoad(String token) {
        Map<String, Claim> claims =
                JWT.require(Algorithm.HMAC256(MallConst.PRIVATE_SIGN)).build().verify(token).getClaims();
        Map<String,String> map = new HashMap<>();
        claims.forEach((k,v) -> {
            map.put(k,v.asString());
        });
        return map;
    }

    /**
     * 获取payLoad里面的特定数据
     * @param token
     * @param fieldName
     * @return
     */
    public static String getFieldValuePayLoad(String token,String fieldName) {
        Map<String, String> payLoad = JWTUtil.getPayLoad(token);
        String fieldValue = payLoad.get(fieldName);
        return fieldValue;
    }
}
